#include <buola/buola.h>
#include <buola/app/ccmdlineoption.h>
#include <buola/app/ccmdline.h>
#include <buola/io.h>
#include <buola/bbox/proxies.h>
#include <buola/bbox/functions.h>

using namespace buola;

static CCmdLineFlag sStatus("status",'s',L"show download status");
static CCmdLineFlag sClick("click",'c',L"a click triggered the download");

int main(int pNArg,char **pArgs)
{
    buola_init(pNArg,pArgs);

    try
    {
        auto lProxy=bbox::get_service("/org/buola/bitdaemon");
        
        if(cmd_line().IsSet(sStatus))
        {
            auto lDownloads=lProxy.Call<std::vector<uint64_t>()>("GetDownloadList");
            msg_info() << lDownloads.size() << "\n";

            for(auto i : lDownloads)
            {
                msg_info() << i << "\n";
                auto lInfo=lProxy.Call<std::tuple<std::wstring,double,double,double>(uint64_t)>("GetDownloadInfo",i);
                msg_info() << std::get<0>(lInfo) << "\n";
                msg_info() << std::get<1>(lInfo) << " " << std::get<2>(lInfo) << " " << std::get<3>(lInfo) << "\n";
            }
        }
        else
        {
            for(const std::string &s : cmd_line().Args())
            {
                io::CURI lURI=io::uri(s);
                lURI.MakeAbsolute(io::get_cwd());
                
                io::CURI lDestination;
                if(cmd_line().IsSet(sClick))
                    lDestination=io::get_home()/"Incoming";
                else
                    lDestination=io::get_cwd();
                
                lProxy.Call<void(io::CURI,io::CURI)>("OpenTorrent",lURI,lDestination);
                sleep(1_s);
            }
        }
    }
    catch(std::exception &pE)
    {
        msg_info() << "caught exception " << pE.what() << "\n";
    }
    
    return buola_finish();
}
